package org.celery.modules.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.celery.modules.goods.entity.Goods;
import org.celery.modules.goods.entity.GoodsStyle;
import org.celery.modules.goods.service.IGoodsService;
import org.celery.modules.order.entity.Order;
import org.celery.modules.order.enums.ShipTypeEnum;
import org.celery.modules.order.excel.OrderExcel;
import org.celery.modules.order.excel.OrderGoodsExcel;
import org.celery.modules.order.vo.OrderVO;
import org.celery.modules.order.mapper.OrderMapper;
import org.celery.modules.order.service.IOrderService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.system.entity.Tenant;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.ITenantService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单表 服务实现类
 *
 * @author Celery
 * @since 2022-04-04
 */
@Service
@AllArgsConstructor
public class OrderServiceImpl extends BaseServiceImpl<OrderMapper, Order> implements IOrderService {

	private final IGoodsService goodsService;
	private final IUserService userService;

	@Override
	public IPage<OrderVO> selectOrderPage(IPage<OrderVO> page, OrderVO order) {
		return page.setRecords(baseMapper.selectOrderPage(page, order));
	}

	@Override
	public List<OrderExcel> exportOrder(Wrapper<Order> queryWrapper) {
		List<Order> orderList = baseMapper.selectList(queryWrapper);
		List<OrderExcel> orderExcelList = new ArrayList<>();
		List<User> userList = userService.list();

		List<Goods> goodsList = goodsService.list();

		for (Order order : orderList) {
			OrderExcel orderExcel = new OrderExcel() {{
				setDestination("台湾");
				setCarrier(ShipTypeEnum.getName(order.getShipType()));
				setAging("空运");
				setGoodsType("普货");
				setOrderCode(order.getCode());
				setShippingCode("");
				setTaoBaoOrderCode("");
				setGoodsCount(order.getGoodsCount().toString());
				setTotalAmount("");
				setGoodsSingleAmount("");
				setGoodsName("");
				setRemark("");
				setShippingGoodsCount("");
				setCollectionOfMoney(order.getTotalAmount().toString());
				setWeight("");
				setStockment("");
				setIsTax("");
				setReceiveName(order.getReceiverName());
				setReceivePhone(order.getReceiverPhone());
				setReceiveTelephone(order.getReceiverPhone());
				setReceiveAddress(order.getShippingAddress());
				setAlternate1(order.getRemark());
			}};

			if (order.getShipType().equals(ShipTypeEnum.SHOP_711_DELIVERY.getType())) {
				String address = order.getShippingAddress();
				orderExcel.setReceiveAddress(address.substring(address.indexOf("-") + 1));
				orderExcel.setStoreNumber(address.substring(address.indexOf("(") + 1, address.indexOf(")")));
				orderExcel.setStoreName(address.substring(0, address.indexOf("(")));
			}

			List<GoodsStyle> goodsStyleList = JsonUtil.parseArray(order.getAssociatedGoods(), GoodsStyle.class);
			for (GoodsStyle goodsStyle : goodsStyleList) {
				for (Goods goods: goodsList) {
					if (goods.getId().equals(goodsStyle.getGoodsId())) {
						// 商品名仅显示一次
						if (Func.isEmpty(orderExcel.getGoodsName())) {
							orderExcel.setGoodsName(goods.getName());
						}
					}
				}
				if (Func.isEmpty(orderExcel.getRemark())) {
					orderExcel.setRemark(goodsStyle.getValue() + " * 1;  ");
				} else {
					orderExcel.setRemark(orderExcel.getRemark() + (orderExcel.getGoodsName().equals("") ? (goodsStyle.getValue() + " * 1") : (goodsStyle.getValue() + "; * 1")));
				}
			}

			for (User user : userList) {
				if (user.getId().equals(order.getFromUser())) {
					orderExcel.setAlternate2(user.getName());
				}
			}
			orderExcelList.add(orderExcel);
		}
		return orderExcelList;
	}

	@Override
	public List<OrderGoodsExcel> exportOrderGoods(Wrapper<Order> queryWrapper) {
		List<Order> orderList = baseMapper.selectList(queryWrapper);
		List<OrderGoodsExcel> orderGoodsExcelList = new ArrayList<>();

		List<Goods> goodsList = goodsService.list();

		for (Order order : orderList) {
			List<GoodsStyle> goodsStyleList = JsonUtil.parseArray(order.getAssociatedGoods(), GoodsStyle.class);
			for (GoodsStyle goodsStyle : goodsStyleList) {
				String goodsName = null;
				// 设置商品名
				for (Goods goods: goodsList) {
					if (goods.getId().equals(goodsStyle.getGoodsId())) {
						goodsName = goods.getName();
					}
				}
				// 如果记录为空,直接追加一条记录
				if (Func.isEmpty(orderGoodsExcelList)) {
					String finalGoodsName = goodsName;
					orderGoodsExcelList.add(new OrderGoodsExcel() {{
						setStyle(goodsStyle.getValue());
						setCount(1);
						setGoodsName(finalGoodsName);
					}});
				} else {
					boolean match = false;
					for (OrderGoodsExcel orderGoodsExcel: orderGoodsExcelList) {
						if (orderGoodsExcel.getGoodsName().equals(goodsName) && orderGoodsExcel.getStyle().equals(goodsStyle.getValue())) {
							orderGoodsExcel.setCount(orderGoodsExcel.getCount()+1);
							match = true;
							break;
						}
					}
					if (!match) {
						String finalGoodsName1 = goodsName;
						orderGoodsExcelList.add(new OrderGoodsExcel() {{
							setGoodsName(finalGoodsName1);
							setStyle(goodsStyle.getValue());
							setCount(1);
						}});
					}
				}
			}
		}
		return orderGoodsExcelList;
	}

	@Override
	public String getOrderCode(String tenantId) {
		String today = DateUtil.formatDate(DateUtil.now());
		Date startTime = DateUtil.parse(today + " 00:00:00", DateUtil.PATTERN_DATETIME);
		Date endTime = DateUtil.parse(today + " 23:59:59", DateUtil.PATTERN_DATETIME);

		// 获取今日该租户订单
		QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().between(Order::getCreateTime, startTime, endTime);

		ITenantService tenantService = SpringUtil.getBean(ITenantService.class);
		Tenant tenant = tenantService.getOne(Wrappers.<Tenant>lambdaQuery().eq(Tenant::getTenantId, tenantId));

		String orderPrefix = Func.isEmpty(tenant) ? "" : tenant.getOrderPrefix();

		if (Func.isNotEmpty(orderPrefix)) {
			queryWrapper.lambda().eq(Order::getTenantId, tenantId);
		}

		List<Order> orderList = list(queryWrapper);

		NumberFormat nf = new DecimalFormat("0000");

		return orderPrefix + DateUtil.format(DateUtil.now(), "yyyyMMdd") + nf.format(orderList.size() + 1) ;
	}

}
